import java.util.ArrayList;
import java.util.List;

/**
 * @author 挚爱之夕
 * @version 1.0
 * @implSpec 中等
 * 数字 n 代表生成括号的对数，请你设计一个函数，用于能够生成所有可能的并且 有效的 括号组合。
 * 输入：n = 3
 * 输出：["((()))","(()())","(())()","()(())","()()()"]
 * @since 2023-09-04 15:07
 */
public class _022括号生成 {
    public static void main(String[] args) {
        System.out.println(generateParenthesis(3));
    }
    static List<String> ans;

    public static List<String> generateParenthesis(int n) {
        ans = new ArrayList<>();
        dfs(new StringBuilder(), 0, 0, n);
        return ans;
    }
    static void dfs(StringBuilder cur, int left, int right, int n){
        if(cur.length() >= n * 2){
            ans.add(cur.toString());
            return;
        }
        if(left < n){
            cur.append("(");
            dfs(cur, left + 1, right, n);
            cur.deleteCharAt(cur.length() - 1);
        }
        if(right < left){
            cur.append(")");
            dfs(cur, left, right + 1, n);
            cur.deleteCharAt(cur.length() - 1);
        }
    }
}
